package com.lt.flashcard.model.service;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.lt.flashcard.Utility;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Generate output from data and template, use FreeMarker as template engine
 * @author ocsen
 *
 */
public class TemplateService {
	
	private String templateFolder = "";
	
	private Configuration configuration = null;

	/**
	 * Init the template service with template folder
	 * @param templatefolder
	 */
	public TemplateService(String templatefolder) {
		this.templateFolder = templatefolder;
		
		configuration = new Configuration();
		try {
			configuration.setDirectoryForTemplateLoading(new File(this.templateFolder));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getTemplateFolder() {
		return templateFolder;
	}

	public void setTemplateFolder(String templateFolder) {
		this.templateFolder = templateFolder;
	}
	
	/**
	 * Cache for template file
	 */
	private Map<String, Template> cacheFile = new HashMap<String, Template>();
	
	/**
	 * Get a template from file system
	 * @param filename the filename without extension
	 * @return
	 */
	public Template getTemplateFile(String filename) {
		if(!cacheFile.containsKey(filename)) {
			Template tpl = null;
			try {
				tpl = configuration.getTemplate(filename.concat(".ftl"), "UTF-8");
				cacheFile.put(filename, tpl);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return cacheFile.containsKey(filename) ? cacheFile.get(filename) : null;
	}
	
	public String parseTemplate(String filename, Map<String, Object> data) {
		Template tpl = getTemplateFile(filename);
		if(tpl == null)
			return "";
		
		if(data == null)
			data = new HashMap<String, Object>();
		
		data.put("baseurl", Utility.getServerUrl());
		
		StringWriter out = new StringWriter();
		try {
			tpl.process(data, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toString();
	}
}
